<?php
namespace Plu\Library\Plugins;

use Phalcon\Mvc\User\Plugin,
    Plu\Library\Services\Permission\PermissionService;

/**
 * 权限管理v2版本
 */
class PermissionCheckerV2Plugin extends Plugin {
    private $_handler;

    public function beforeExecuteRoute($event, $dispatcher) {
        $annotations = $this->annotations->getMethod(
        	$dispatcher->getControllerClass(),
        	$dispatcher->getActiveMethod()
        );

        if ($annotations->has('checkPermission')) {
        	$annotation = $annotations->get('checkPermission');
        	$this->checkAdminPermission($annotation);
        }
    }

    public function afterExecuteRoute($event, $dispatcher) {
        $annotations = $this->annotations->getMethod(
            $dispatcher->getControllerClass(),
            $dispatcher->getActiveMethod()
        );
    }

    /**
     * 登录体系使用权限系统的一套
     */
    private function checkLogin() {
        if (!$this->_handler) {
            $this->_handler = new PermissionService;
        }

        if (!$this->_handler->checkLogin()) {
            return $this->_handler->login();
        }

        return $this->_handler->checkLogin();
    }

    private function throwStatus406() {
        $this->response->setStatusCode(406, "Not Acceptable");
        $this->response->send();
        exit;
    }

    /**
     * 检查管理员权限
     * @param 传入参数只需要 tag
     */
    private function checkAdminPermission($annotation) {
        $isLogined = $this->checkLogin();

        if (!is_bool($isLogined)) {
            return $isLogined;
        }

        $config = $this->config['permission'];

		$tag = $annotation->getNamedArgument('tag');
        $functionId = $config['acl'][$tag];

        if (empty($functionId)) {
            return true;
        }

        $isAccessed = $this->_handler->checkPermission($functionId);
        //计算当前的role是否符合此权限
        if ($isAccessed == false) {
        	return $this->throwStatus406();
        }
    }
}
?>
